import { createAlova } from 'alova'
import VueHook from 'alova/vue'
import { defaultHttpAdapter, mockAdapter } from './mock'
import { Code, type ApiResponse } from './type'

export const alovaInstance = createAlova({
  baseURL: import.meta.env.VITE_GLOB_API_URL + import.meta.env.VITE_GLOB_API_URL_PREFIX,
  timeout: 5000,
  statesHook: VueHook,
  requestAdapter: import.meta.env.DEV ? mockAdapter : defaultHttpAdapter,
  responded: async (response, method) => {
    const { showErrorModal = false, showMsg = false } = method.meta || {}
    const apiRes = (await response.json()) as ApiResponse
    if (apiRes.code === Code.ERROR) {
      if (showErrorModal) {
        console.log(apiRes.msg)
      }
    } else if (apiRes.code === Code.NOT_LOGIN) {
      console.log(apiRes.msg)
    }
    if (showMsg) {
      console.log(apiRes.msg)
    }
    return apiRes.data
  },
  beforeRequest(method) {
    const userStore = useUserStore()
    // 忽略token 如果忽略token 则不添加token
    const { ignoreToken = false } = method.meta || {}
    if (!ignoreToken && userStore.isLogin) {
      method.config.headers['Authorization'] = 'token ' + userStore.token
    }
  },
})
